#!/bin/bash

BIN_DIR=/usr/local/docker/bin

[ $# -ne 1 ] && echo "Usage $0 {install|uninstall}"

install(){
setenforce 0
sed -i 's#SELINUX=.*#SELINUX=disabled#' /etc/selinux/config

[ -d $BIN_DIR ] || mkdir -p $BIN_DIR
curl -OL https://ftp.hc-yun.com/docker/docker-install-bin/docker-18.09.4.tgz
tar xvf docker-18.09.4.tgz -C $BIN_DIR --strip-components 1
rm -f docker-18.09.4.tgz
[ $(grep "# docker path" ~/.bashrc | wc -l) -eq 0 ] && echo -e "\n# docker path\nPATH=$BIN_DIR:\$PATH" >> ~/.bashrc

[ -d /etc/docker ] || mkdir /etc/docker
cat > /etc/docker/daemon.json <<'EOF'
{
  "registry-mirrors": ["http://3272dd08.m.daocloud.io", "https://docker.mirrors.ustc.edu.cn"],
  "max-concurrent-downloads": 10,
  "log-driver": "json-file",
  "log-level": "warn",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
    },
  "data-root": "/var/lib/docker",
  "hosts": ["tcp://0.0.0.0:2376", "unix:///var/run/docker.sock"]
}
EOF

cat > /etc/systemd/system/docker.service <<EOF
[Unit]
Description=Docker Application Container Engine
Documentation=http://docs.docker.io
After=keepalived.service glusterd.service autofs.service

[Service]
Type=idle
Environment="PATH=$BIN_DIR:/bin:/sbin:/usr/bin:/usr/sbin"
ExecStart=$BIN_DIR/dockerd
ExecStartPost=/sbin/iptables -I FORWARD -s 0.0.0.0/0 -j ACCEPT
ExecReload=/bin/kill -s HUP $MAINPID
Restart=on-failure
RestartSec=5
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
Delegate=yes
KillMode=process

[Install]
WantedBy=multi-user.target
EOF

iptables -P INPUT ACCEPT
iptables -F
iptables -X
iptables -F -t nat
iptables -X -t nat
iptables -F -t raw
iptables -X -t raw
iptables -F -t mangle
iptables -X -t mangle

systemctl daemon-reload
systemctl start docker
systemctl enable docker

curl -o /usr/local/bin/docker-compose https://ftp.hc-yun.com/docker/docker-install-bin/docker-compose
chmod +x /usr/local/bin/docker-compose

source ~/.bashrc
docker -v
echo -e '\n\n'
docker-compose -v
}

uninstall(){
    systemctl stop docker
    systemctl disable docker
    rm -rf $BIN_DIR
    rm -f /etc/docker/daemon.json
    rm -f /etc/systemd/system/docker.service
    rm -f /usr/local/bin/docker-compose
}

case "$1" in
    install) install
    ;;
    uninstall) uninstall
    ;;
    *) echo "Usage $0 {install|uninstall}"
esac
